package com.srit.forecast.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.srit.core.bean.Page;
import com.srit.forecast.bean.Report;
import com.srit.forecast.constant.Constant;
import com.srit.forecast.dao.ReportDao;

/**
 * 报文Dao
 * 
 * @author guan
 * 
 */
@Service
@Transactional
public class ReportDaoImpl implements ReportDao {
	@Autowired(required = true)
	private JdbcTemplate jdbcTemplate;

	@Override
	public int getMaxId() {
		String sql = "select max(ID) from TI_REPORT";
		return jdbcTemplate.queryForInt(sql);
	}

	@Override
	public void save(Report report) {
		String sql = "insert into TI_REPORT (ID,PUBFLAG,PUBTIME,CREATOR,COMMITTIME,DELETED,TYPE,STATUS,YEAR,MONTH,DAY,HOUR) "
				+ "values(SEQ_TI_REPORT.nextval,?,?,?,?,?,?,?,?,?,?,?)";
		jdbcTemplate.update(
				sql,
				new Object[] { report.getPubFlag(), report.getPubTime(),
						report.getCreator(), report.getCommitTime(),
						report.getDeleted(), report.getType(),
						report.getStatus(), report.getYear(),
						report.getMonth(), report.getDay(), report.getHour() });
	}

	@Override
	public Report getById(Integer id) {
		String sql = "select * from TI_REPORT where id=?";
		return jdbcTemplate.queryForObject(sql, new Object[] { id },
				new ReportRowMapper());
	}

	@Override
	public void delete(Integer id) {
		String sql = "update TI_REPORT set DELETED=? where id=?";
		jdbcTemplate.update(sql, new Object[] { Constant.DELETED, id });
	}

	@Override
	public void update(Report t) {
		// TODO Auto-generated method stub

	}

	@Override
	public void page(Page page) {
		// TODO Auto-generated method stub

	}

}

class ReportResultSetExtractor implements ResultSetExtractor {

	@Override
	public Object extractData(ResultSet rs) throws SQLException,
			DataAccessException {
		Report re = new Report();
		// ID,NAME,CODE,TYPE,REMARK,DELETED,ENABLED
		re.setId(rs.getInt("ID"));
		re.setCommitTime(rs.getDate("COMMITTIME"));
		re.setDeleted(rs.getString("DELETED"));
		re.setPubFlag(rs.getString("PUBFLAG"));
		re.setPubTime(rs.getDate("PUBTIME"));
		re.setType(rs.getString("TYPE"));
		re.setStatus(rs.getString("STATUS"));
		re.setYear(rs.getInt("YEAR"));
		re.setMonth(rs.getInt("MONTH"));
		re.setDay(rs.getInt("DAY"));
		re.setHour(rs.getInt("HOUR"));
		return re;
	}

}

class ReportRowMapper implements RowMapper {
	@Override
	public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
		ReportResultSetExtractor extractor = new ReportResultSetExtractor();
		return extractor.extractData(rs);
	}

}
